package com.bdsy.business.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.bdsy.business.dao.IntroGoodMapper;
import com.bdsy.business.model.IntroGood;
import com.bdsy.business.service.IntroGoodService;
import com.bdsy.common.utils.DateUtil;
import com.bdsy.common.utils.ZipUtil;


@Service("introGoodService")
public class IntroGoodServiceImpl implements IntroGoodService {

	@Autowired
	IntroGoodMapper introGoodMapper;
	
	@Override
	public List<Map> selectIntroGoodList() {
		@SuppressWarnings("rawtypes")
		List<Map> introGoodList = introGoodMapper.selectIntroGoodList();
		return introGoodList;
	}

	@Override
	public boolean insert(MultipartFile file,IntroGood introGood) {
		introGood.setId((int)((Math.random()*9+1)*10000000));
		introGood.setTime(DateUtil.getCurrentDate());
		
		//服务器项目目录路径
		String path = "/usr/local/tomcat/webapps/adicms_image/iroges";
		//文件名
		//  String fileName = file.getOriginalFilename();
		if(file !=null){
			//文件类型
			String contentType = file.getContentType();
			//获得文件后缀名   
		    String suffixName=contentType.substring(contentType.indexOf("/")+1); 
		    //生成uuid作为文件名称    
		    String uuid = UUID.randomUUID().toString().replaceAll("-","");    
		    //得到 文件名  
		    String fileName=uuid+"."+suffixName;  
		    
		    System.out.println(path+"--***---"+contentType+"--***---"+suffixName+"---***---"+fileName);
			//生成文件
		    File dir = new File(path, fileName);  
		    if(!dir.exists()){  
		        dir.mkdirs();  
		    }   
		    System.out.println(dir.getAbsolutePath()+"///////");
		    try {
				file.transferTo(dir);
			}catch (IOException e) {
				System.out.println("文件转换失败");
				e.printStackTrace();
			}
		    
		    //解压缩上传的照片
		    File upload = new File(path);//解压文件存储的路径
			List<File> list = ZipUtil.upzipFiles(dir, upload.getAbsolutePath());
			//删除压缩文件
			ZipUtil.deletefile(dir.toString());
			System.out.println(list+"///////-----");
			
			String iroges = "";
			for (File file2 : list) {
				iroges += file2.toString()+";";
			}
			introGood.setImges(iroges);
		}
		
		int result = introGoodMapper.insert(introGood);
		return result>0?true:false;
	}

	@Override
	public boolean update(IntroGood introGood) {
		int result = introGoodMapper.update(introGood);
		return result>0?true:false;
	}

	@Override
	public boolean delete(List<String> pIds) {
		int result = introGoodMapper.delete(pIds);
		return result>0?true:false;
	}

	@Override
	public List<IntroGood> introGoodById(int id) {
		List<IntroGood> introGood = introGoodMapper.introGoodById(id);
		return introGood;
	}

}
